package com.zzl.finance.data.service.impl;

import com.zzl.finance.data.constant.StringConstant;
import com.zzl.finance.data.dto.FinanceScopeInfoDto;
import com.zzl.finance.data.entity.FinanceInstitutyEntity;
import com.zzl.finance.data.service.FinanceInstitutyService;
import com.zzl.general.common.exception.SysException;
import com.zzl.general.common.serurity.entity.User;
import com.zzl.general.common.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzl.general.common.utils.PageUtils;
import com.zzl.general.common.utils.Query;

import com.zzl.finance.data.dao.FinanceScopeDao;
import com.zzl.finance.data.service.FinanceScopeService;
import com.zzl.finance.data.entity.FinanceScopeEntity;
import com.zzl.finance.data.dto.FinanceScopeAddDto;
import com.zzl.finance.data.dto.FinanceScopeUpdateDto;
import org.springframework.util.CollectionUtils;

/**
 * 资金方融资范围
 *
 * @author gull
 * @date 2022-07-01 18:23:11
 */
@Service("financeScopeService")
public class FinanceScopeServiceImpl extends ServiceImpl<FinanceScopeDao, FinanceScopeEntity> implements FinanceScopeService {

    @Autowired
    private FinanceInstitutyService financeInstitutyService;

    /**
     * 分页查询
     *
     * @param params 查询参数
     * @return 分页数据
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<FinanceScopeEntity> page = this.page(
                new Query<FinanceScopeEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 新增
     *
     * @param financeScopeAddDto 新增实体
     * @param user               当前登录用户
     * @throws SysException 业务异常
     */
    @Override
    public void saveFinanceScope(FinanceScopeAddDto financeScopeAddDto, User user) throws SysException {
        FinanceScopeEntity financeScopeEntity = new FinanceScopeEntity();
        BeanUtils.copyProperties(financeScopeAddDto, financeScopeEntity);
        financeScopeEntity.setCreatorId(user.getId());
        if (!this.save(financeScopeEntity)) {
            throw new SysException("A00001", "保存失败！");
        }
    }

    /**
     * 修改
     *
     * @param financeScopeUpdateDto 修改实体
     * @param user                  当前登录用户
     * @throws SysException 业务异常
     */
    @Override
    public void updateFinanceScopeById(FinanceScopeUpdateDto financeScopeUpdateDto, User user) throws SysException {
        FinanceScopeEntity financeScopeEntity = new FinanceScopeEntity();
        BeanUtils.copyProperties(financeScopeUpdateDto, financeScopeEntity);
        financeScopeEntity.setUpdaterId(user.getId());
        if (!this.updateById(financeScopeEntity)) {
            throw new SysException("A00002", "修改失败！");
        }
    }

    /**
     * 根据资金方查询融资范围
     *
     * @param id 资金方id
     */
    @Override
    public List<FinanceScopeInfoDto> getFinanceScopeByfinanceId(String id) {
        List<FinanceScopeInfoDto> scopeInfoDtoList = new ArrayList<>();
        QueryWrapper<FinanceScopeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FinanceScopeEntity::getInstitutyId, id);
        List<FinanceScopeEntity> list = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            List<String> collect = list.stream().map(FinanceScopeEntity::getInstitutyScopeId)
                    .distinct().collect(Collectors.toList());
//            若融资范围是0，则查询全部
            if (collect.contains(StringConstant.INSTITUTY_SCOPE_ID)) {
                FinanceScopeInfoDto financeScopeInfoDto = new FinanceScopeInfoDto();
                financeScopeInfoDto.setInstitutyScopeName("全部");
                scopeInfoDtoList.add(financeScopeInfoDto);
            } else {
                QueryWrapper<FinanceInstitutyEntity> financeQueryWrapper = new QueryWrapper<>();
                financeQueryWrapper.lambda().in(FinanceInstitutyEntity::getId, collect);
                List<FinanceInstitutyEntity> institutyEntities = financeInstitutyService.list(financeQueryWrapper);
                Map<String, String> collect1 = institutyEntities.stream()
                        .collect(Collectors.toMap(FinanceInstitutyEntity::getId, FinanceInstitutyEntity::getInstinctyName));
                list.forEach(x -> {
                    FinanceScopeInfoDto financeScopeInfoDto = new FinanceScopeInfoDto();
                    BeanUtils.copyProperties(x, financeScopeInfoDto);
                    financeScopeInfoDto.setInstitutyScopeName(collect1.get(x.getInstitutyScopeId()));
                    scopeInfoDtoList.add(financeScopeInfoDto);

                });
            }
        }
        return scopeInfoDtoList;
    }

    /**
     * 保存融资范围
     *
     * @param financingScope 融资范围id
     * @param institutyId    资金方id
     * @param user           用户
     */
    @Override
    public void saveBatchFinanceScope(List<String> financingScope, String institutyId, User user) throws SysException {
        if (!CollectionUtils.isEmpty(financingScope)) {
            List<FinanceScopeEntity> list = new ArrayList<>(financingScope.size());
            financingScope.forEach(x -> {
                FinanceScopeEntity financeScopeEntity = new FinanceScopeEntity();
                financeScopeEntity.setId(UuidUtils.UUID());
                financeScopeEntity.setInstitutyScopeId(x);
                financeScopeEntity.setInstitutyId(institutyId);
                financeScopeEntity.setCreatorId(user.getId());
                financeScopeEntity.setUpdaterId(user.getId());
                list.add(financeScopeEntity);
            });
            if (!this.saveBatch(list)) {
                throw new SysException("融资范围保存失败");
            }

        }
    }

}